﻿using ProjectFootball.MVC.Foundation.ResourceLibrary;
using ProjectFootball.MVC.Models;
using ProjectFootball.MVC.Models.EntityFramework.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace ProjectFootball.MVC.Areas.CompetitionArea.Models
{
    public class CompetitionViewModel
    {
        public CompetitionDataModel CompetitionDataModel { get; set; }
        public CompetitionSearchResultViewModel CompetitionSearchResultViewModel { get; set; }
        public IEnumerable<Match> Matches { get; set; }
        
        public IEnumerable<LeagueTableItemViewModel> LeagueTable 
        {
            get
            {
                if (Matches == null)
                    return null;

                List<LeagueTableItemViewModel> leagueTable = new List<LeagueTableItemViewModel>();

                foreach (var match in Matches)
                {
                    var leagueTableItem1ViewModel = leagueTable.GetLeagueTableItem(match.Team1Guid);

                    if (leagueTableItem1ViewModel == null)
                    {
                        leagueTableItem1ViewModel = new LeagueTableItemViewModel() { TeamVersion = match.TeamVersion1 };
                        leagueTable.Add(leagueTableItem1ViewModel);
                    }

                    var leagueTableItem2ViewModel = leagueTable.GetLeagueTableItem(match.Team2Guid);

                    if (leagueTableItem2ViewModel == null)
                    {
                        leagueTableItem2ViewModel = new LeagueTableItemViewModel() { TeamVersion = match.TeamVersion2 };
                        leagueTable.Add(leagueTableItem2ViewModel);
                    }

                    switch (Math.Sign((short)match.Team1FT - (short)match.Team2FT))
                    {
                        case 1:
                            leagueTableItem1ViewModel.HomeWins++;
                            leagueTableItem2ViewModel.AwayLosses++;
                            break;

                        case 0:
                            leagueTableItem1ViewModel.HomeDraws++;
                            leagueTableItem2ViewModel.AwayDraws++;
                            break;

                        case -1:
                            leagueTableItem1ViewModel.HomeLosses++;
                            leagueTableItem2ViewModel.AwayWins++;
                            break;
                    }

                    leagueTableItem1ViewModel.HomeScored += (int)match.Team1FT;
                    leagueTableItem1ViewModel.HomeConceded += (int)match.Team2FT;

                    leagueTableItem2ViewModel.AwayConceded += (int)match.Team1FT;
                    leagueTableItem2ViewModel.AwayScored += (int)match.Team2FT;
                }

                leagueTable.Sort();

                return leagueTable;
            }
        }

        
    }
}